package com.hz.house.service.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hz.house.bean.entity.ZhongqiuActivityBean;
import com.hz.house.bean.entity.ZhongqiuActivityHeplerBean;
import com.hz.house.cache.ZhongqiuActivityCacheService;
import com.hz.house.common.ResultUtil;
import com.hz.house.dao.ZhongqiuActivityMapper;
import com.hz.house.token.CurrentUser;

import lombok.extern.slf4j.Slf4j;

/**
 * 中秋活动业务层
 * @author lfw
 */
@Service
@Slf4j
public class ZhongqiuActivityService {
	
	@Autowired
	private ZhongqiuActivityMapper zqMapper;
	
	@Autowired
	private ZhongqiuActivityCacheService zqCacheService;
	
	/**
	 * 加入中秋活动
	 * @return
	 */
	public  Object joinActivity() {
		try {
			
			int x = this.zqMapper.joinInActivity(CurrentUser.getCurrentUserId());
			if(x>0) {
				//执行缓存总人数自增
				this.zqCacheService.incrementTotalCount();
				return ResultUtil.ok();
			}
				
		} catch (Exception e) {
			if(e instanceof DuplicateKeyException)
				return ResultUtil.fail("你已经参与活动了");
			e.printStackTrace();
			log.error("参与活动异常",e);
		}
		return ResultUtil.fail("参与失败,请重试");
	}
	
	
	/**
	 * 帮好友助力
	 * @param friendId
	 * @param helperId
	 * @return
	 */
	public Object helpFriends(Integer friendId) {
		
		if(friendId==null)
			return ResultUtil.fail("用户不存在");
		int myid = CurrentUser.getCurrentUserId();
		if(friendId.intValue()==myid)
			return ResultUtil.fail("不能自己给自己助力哦");
		try {
			//先查询用户是否已经给别人助力过了，一个人只能给一个人助力
			int z = this.zqMapper.getHelperCount(myid);
			if(z>0)
				return ResultUtil.fail("已为别人助力");
			//执行助力
			int x = this.zqMapper.helpFriends(friendId,CurrentUser.getCurrentUserId());
			if(x>0) {
				//如果被助力的用户有缓存信息，要把助力人数+1
				this.zqCacheService.incrementHelperCounts(friendId);
				return ResultUtil.ok("助力成功");
			}
				
		} catch (Exception e) {
			if(e instanceof DuplicateKeyException)
				return ResultUtil.fail("您已助力");
			e.printStackTrace();
			log.error("助力异常",e);
		}
		return ResultUtil.fail("助力失败,请重试");
	}
	
	
	public Object getUserInfo() {
		//我自己的id
		int myId = CurrentUser.getCurrentUserId();
		ZhongqiuActivityBean zq = null;
		zq = getActzbFromCache(myId);//查询我自己的不差点赞
		if(zq==null) {
			zq = new ZhongqiuActivityBean();
			zq.setHasJoin(0);
			zq.setHelperCounts(0);
			zq.setMyId(myId);
			zq.setHelpers(new ArrayList<>(0));
			zq.setHasHelped(0);
		}else {
			if(zq.getHasHelped()==null)
				zq.setHasHelped(0);
			if(zq.getHelpers()==null)
				zq.setHelpers(new ArrayList<>());
			if(zq.getHelperCounts()==null)
				zq.setHelperCounts(0);
		}
		//获取参与总人数
		zq.setTotalCounts(getTotal()+10000);
		return ResultUtil.ok(zq);
	}
	
	
	private int getTotal() {
		Integer total = this.zqCacheService.getCacheTotalCount();
		if(total==null) {
			total = this.zqMapper.getTotalParticipantCount();
			this.zqCacheService.setCacheTotalCount(total);
		}
		return total;
	}
	
	/**
	 * 用户分享进入助力页面，查询被助力者的数据
	 * @param hisId
	 * @return
	 */
	public Object getHisInfo(Integer hisId) {
		if(hisId==null) {
			log.error("请求的hisId为空");
			return ResultUtil.fail("用户不存在");
		}
		ZhongqiuActivityBean zq = getActzbFromCache(hisId);
		if(zq==null) {
			log.info("用户["+hisId+"]还未参与活动");
			return ResultUtil.fail("无该用户活动信息");
		}
		int x = this.zqMapper.getIHasHelped(CurrentUser.getCurrentUserId(), hisId);
		zq.setHasHelped(x);
		if(zq.getHelpers()==null)
			zq.setHelpers(new ArrayList<>(0));
		zq.setMyId(null);
		//获取参与总人数
		zq.setTotalCounts(getTotal()+10000);
		return ResultUtil.ok(zq);
	}
	
	//缓存用户主页信息代码
	private ZhongqiuActivityBean getActzbFromCache(Integer hisId) {
		
		ZhongqiuActivityBean zq= this.zqCacheService.getZhongqiuUserInfoCache(hisId);
		if(zq==null) {
			//查询用户信息
			zq = this.zqMapper.getUserState(hisId);
			if(zq==null) {
				log.info("用户["+hisId+"]还未参与活动");
				return null;
			}
			
			zq.setHasJoin(1);
			//如果助力者数量大于0，查询最近3个助力者的信息返回前台展示
			if(zq.getHelperCounts()!=null && zq.getHelperCounts()>0) {
				List<ZhongqiuActivityHeplerBean> hnames = this.zqMapper.getHelperFor3(hisId);
				hnames.forEach(h->{
					if(StringUtils.isEmpty(h.getName()))
						h.setName("_-");
				});
				zq.setHelpers(hnames);
			}else {
				zq.setHelperCounts(0);
				//zq.setHelpers(new ArrayList<>(0));
			}
			
			//初始化缓存  缓存10分钟
			this.zqCacheService.setUserSelfCache(zq);
			return zq;
		}
		//判断助力者是否大于5人，且帮助者集合是否等于5，否则重新拉取助力者数据
		List<ZhongqiuActivityHeplerBean> hnames=zq.getHelpers();
		if(zq.getHelperCounts()==0)
			return zq;
		//助力者小于等于5且与要在前端显示的名字数量相同，则直接返回，不用刷新
		if(zq.getHelperCounts()<=5 && (hnames!=null && hnames.size()==zq.getHelperCounts()))
			return zq;
		//助力者大于5且要显示的人数等于5，则不用刷新
		if(zq.getHelperCounts()>5&& (hnames!=null && hnames.size()==5))
			return zq;
		log.info("重新拉取前5个助力者....");
		List<ZhongqiuActivityHeplerBean> xns= this.zqMapper.getHelperFor3(hisId);
		System.out.println(xns.size());
		xns.forEach(h->{
			if(StringUtils.isEmpty(h.getName()))
				h.setName("_-");
		});
		zq.setHelpers(xns);
		//重新覆盖原值
		this.zqCacheService.setUserSelfCache(zq);
		return zq;
	}
	
	
	
	
	/**
	 * 分页查询的助力者信息
	 * @param page
	 * @return
	 */
	public  Object searchHelpersPage(Integer page,Integer hisId) {
		if(page==null)
			page=1;
		int myid = CurrentUser.getCurrentUserId();
		page = (page-1)*10;
		Map<String,Object> m = new HashMap<>();
		m.put("page", page);
		m.put("size", 10);
		if(hisId!=null)
			m.put("userId", hisId);
		else
			m.put("userId", myid);
		List<ZhongqiuActivityHeplerBean> helpers = this.zqMapper.searchHelpers(m); 
		
		if(helpers.size()>0) {
			helpers.forEach(h->{
				if(StringUtils.isEmpty(h.getName()))
					h.setName("_-");
				if(StringUtils.isEmpty(h.getHeadUrl()))
					h.setHeadUrl("https://housessmall-dev-index-img-1258778894.cos"
							+ ".ap-chengdu.myqcloud.com/icon/tx.png");//给一个默认的头像，不然报错
			});
		}
		
		int total = this.zqMapper.searchHelpersCounts(m);
		m.clear();
		m.put("total", total);
		m.put("rows", helpers);
		return ResultUtil.ok(m);
	}
	
	public void test() {
		zqCacheService.incrementTotalCount();
	}
	
	
}
